package cn.bocweb.spinning.view.common;

import android.app.DownloadManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import java.io.File;

/**
 * 下载service
 */
public class UpdataService extends Service {


    private final static String ALBUM_PATH = Environment.getExternalStorageDirectory() + "/cn.bocweb.spinning.file/";

    /**
     * 安卓系统下载类
     **/
    DownloadManager manager;

    /**
     * 接收下载完的广播
     **/
    DownloadCompleteReceiver receiver;

    /**
     * 初始化下载器
     **/
    private void initDownManager(String url) {

        manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

        receiver = new DownloadCompleteReceiver();


        //设置下载地址
        DownloadManager.Request down = new DownloadManager.Request(
                Uri.parse(url));

        // 设置允许使用的网络类型，这里是移动网络和wifi都可以
        down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
                | DownloadManager.Request.NETWORK_WIFI);

        // 下载时，通知栏显示途中
        down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);

        // 显示下载界面
        down.setVisibleInDownloadsUi(true);

        File dirFile = new File(ALBUM_PATH);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        // 设置下载后文件存放的位置
//        if (Build.VERSION.SDK_INT >= 23) {
//            int filePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
//            if (filePermission != PackageManager.PERMISSION_GRANTED) {
//                ActivityCompat.requestPermissions(this, );
//            }
//        } else {
        down.setDestinationInExternalPublicDir("cn.bocweb.spinning.file", "spinningschool.apk");
//        }
//        }
//        else {
//            down.setDestinationInExternalPublicDir("cn.bocweb.hl.file", "51Charge");
//        }
//        down.setDestinationInExternalFilesDir(
//                ALBUM_PATH, "泰捷面签");

        // 将下载请求放入队列
        manager.enqueue(down);

        //注册下载广播
        registerReceiver(receiver, new IntentFilter(
                DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        String url = intent.getStringExtra("url");
        // 调用下载
        initDownManager(url);

        return Service.START_NOT_STICKY;
        //  return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    @Override
    public void onDestroy() {

        // 注销下载广播
        if (receiver != null)
            unregisterReceiver(receiver);

        super.onDestroy();
    }

    // 接受下载完成后的intent
    class DownloadCompleteReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {


            //判断是否下载完成的广播
            if (intent.getAction().equals(
                    DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {

                //获取下载的文件id
                long downId = intent.getLongExtra(
                        DownloadManager.EXTRA_DOWNLOAD_ID, -1);

                //自动安装apk
                installAPK(manager.getUriForDownloadedFile(downId));

                //停止服务并关闭广播
                UpdataService.this.stopSelf();

            }
        }

        /**
         * 安装apk文件
         */
        private void installAPK(Uri apk) {

            if (Build.VERSION.SDK_INT < 23) {
                // 通过Intent安装APK文件
                Intent intents = new Intent();

                intents.setAction("android.intent.action.VIEW");
                intents.addCategory("android.intent.category.DEFAULT");
                intents.setType("application/vnd.android.package-archive");
                intents.setData(apk);
                intents.setDataAndType(apk, "application/vnd.android.package-archive");
                intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            android.os.Process.killProcess(android.os.Process.myPid());
                // 如果不加上这句的话在apk安装完成之后点击单开会崩溃
                startActivity(intents);
            } else {
                File file = new File(ALBUM_PATH + "spinningschool.apk");
                if (file.exists()) {
                    openFile(file, getApplicationContext());
                }
            }
        }

        public void openFile(File var0, Context var1) {
            Intent var2 = new Intent();
            var2.addFlags(268435456);
            var2.setAction("android.intent.action.VIEW");
            String var3 = getMIMEType(var0);
            var2.setDataAndType(Uri.fromFile(var0), var3);
            try {
                var1.startActivity(var2);
            } catch (Exception var5) {
                var5.printStackTrace();
                Toast.makeText(var1, "没有找到打开此类文件的程序", Toast.LENGTH_SHORT).show();
            }

        }

        public String getMIMEType(File var0) {
            String var1 = "";
            String var2 = var0.getName();
            String var3 = var2.substring(var2.lastIndexOf(".") + 1, var2.length()).toLowerCase();
            var1 = MimeTypeMap.getSingleton().getMimeTypeFromExtension(var3);
            return var1;
        }
    }
}